package buaa.qel.rpc.client.asyc;

import buaa.qel.rpc.common.message.RpcResponseMessage;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import lombok.extern.slf4j.Slf4j;

/**
 * promise强化类，用于在接收到response后设置promise任务的完成
 * 令提供响应时间监控机制，警告超时响应
 */
@Slf4j
public class RpcPromise extends DefaultPromise<Object> {
    private long startTime;
    private static final long RESPONSE_TIME_THRESHOLD = 5000L;

    public RpcPromise(EventExecutor executor){
        super(executor);
        this.startTime = System.currentTimeMillis();
    }

    public void done(RpcResponseMessage response,RpcPromise promise) {
        long responseTime = System.currentTimeMillis() - startTime;
        if (responseTime > this.RESPONSE_TIME_THRESHOLD) {
            log.warn("Service response time is too slow. Request id = " + response.getSequenceId() + ". Response Time = " + responseTime + "ms");
        }
        Object returnValue = response.getReturnValue();
        Exception exceptionValue = response.getExceptionValue();
        if(exceptionValue != null) {
            promise.setFailure(exceptionValue);
        } else {
            promise.setSuccess(returnValue);
        }
    }
}
